package com.mycompany.test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;


public class SonarJsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }
  
  public static void printJson(String uglyJSONString){
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      JsonParser jp = new JsonParser();
      JsonElement je = jp.parse(uglyJSONString);
      String prettyJsonString = gson.toJson(je);
      System.out.println(prettyJsonString);
  }
  
  public void printIssuesJson(){
      try {
          JSONObject json = readJsonFromUrl("http://localhost:9000/api/issues/search");
          printJson(json.toString());
      } catch (IOException ex) {
          Logger.getLogger(SonarJsonReader.class.getName()).log(Level.SEVERE, null, ex);
      } catch (JSONException ex) {
          Logger.getLogger(SonarJsonReader.class.getName()).log(Level.SEVERE, null, ex);
      }
  }

  public static void main(String[] args) throws IOException, JSONException {
    new SonarJsonReader().printIssuesJson();
  }
}